var debounce = function(idle, action){
  var last;
  return function(){
    var ctx = this, args = arguments;
    clearTimeout(last);
    last = setTimeout(function(){
        action.apply(ctx, args);
    }, idle);
  }
}

$("#searchAch").keyup(debounce(230, function(e){
  var current = $("#searchAch").val().trim().toLowerCase();
  if(current == '') {
    $(".post-item").show();
    return;
  }
  $(".post-item").each(function(){
    var title = $(this).find(".post-ach-title").text().toLowerCase();
    var hit = false;
    if(title.indexOf(current) != -1) hit = true;
    else {
      $(this).find(".post-tag").each(function(){
        if($(this).text().toLowerCase().indexOf(current) != -1) hit = true;
      });
    }
    hit ? $(this).show() : $(this).hide();
  });
}));

// img 标签点击放大缩小
$(".post-content img").click(function() {
  var url = $(this).attr('src');
  var img = new Image();
  img.src = url;
  console.log('width:'+img.width+',height:'+img.height);
  var maxHeight = $('body').height() - 150;
  var maxWidth = $('body').width() - 150;
  var modalEle = null
  // fit height at first, if there is very high img
  if (maxHeight < img.height) {
    modalEle = $('<div class="img-modal" onclick="hideImgModal(this)"><img height="' + maxHeight + '" src="' + url + '" /></div>')
  } else if(maxWidth < img.width) {
    // fit width then, if there is very wide img
    modalEle = $('<div class="img-modal" onclick="hideImgModal(this)"><img width="' + maxWidth + '" src="' + url + '" /></div>');
  } else {
    // original width
    modalEle = $('<div class="img-modal" onclick="hideImgModal(this)"><img width="' + img.width + '" src="' + url + '" /></div>');
  }
  modalEle.appendTo('body').show(300);
})

window.hideImgModal = function(ele) {
  $(ele).hide(300, function() {
    $(ele).remove()
  })
}